package com.ray.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.ibatis.annotations.Case;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.google.appengine.repackaged.com.google.protobuf.Internal.DoubleList;
import com.ray.bean.AttendanceMonthSummaryBean;
import com.ray.bean.CompanyMaterialTableBean;
import com.ray.bean.DatatablesViewPageBean;
import com.ray.bean.FeedingAndReportBean;
import com.ray.bean.OrderBean;
import com.ray.bean.ProcessBean;
import com.ray.bean.WarehouseInOutDetailBean;
import com.ray.mapper.OrderCostGlassesMapper;
import com.ray.pojo.ApplyRepairMoneyPojo;
import com.ray.pojo.FeedOrderDetailPojo;
import com.ray.pojo.MaterialSelectFilterPojo;
import com.ray.pojo.OrderCostGlassesPojo;

/**
 * 获取订单成本
* <p>Title: OrderCostGlassesService</p>  
* <p>Description: </p>  
* @author 李斌  
* @date 2018年8月5日
 */
@Service
public class OrderCostGlassesService {
	
	@Autowired
	OrderCostGlassesMapper orderCostGlassesMapper;
	@Autowired
	AttendanceService attendanceService;
	
	/**
	 * 根据订单编号获取非样式五的总投料数
	 * @param feedOrderDetailPojos
	 * @return
	 */
	public int getAllFeedTotal(List<FeedOrderDetailPojo> feedOrderDetailPojos,String orderId) {
		int allFeedTotal = 0;
		for(FeedOrderDetailPojo feedOrderDetailPojo:feedOrderDetailPojos) {
			//订单编号相同,并且行号不是-1
			if(orderId.equals(feedOrderDetailPojo.getOrderId()) && !"-1".equals(feedOrderDetailPojo.getLineNo()) ) {
				allFeedTotal+=feedOrderDetailPojo.getFeedTotal();
			}
		}
		return allFeedTotal;
	}
	
	/**
	 * 获取
	 * @param feedOrderDetailPojos
	 * @param orderId
	 * @param lineNo
	 * @return
	 */
	public Double getAllLineFeedTotal(List<FeedOrderDetailPojo> feedOrderDetailPojos,String orderId,String lineNo,boolean isOrderTotal) {
		Double allFeedTotal = 0.0;
		if(!isOrderTotal) {
			for(FeedOrderDetailPojo feedOrderDetailPojo:feedOrderDetailPojos) {
				//订单编号相同,并且行号不是-1
				if(orderId.equals(feedOrderDetailPojo.getOrderId())) {
					if(!"-1".equals(feedOrderDetailPojo.getLineNo()) && lineNo.equals(feedOrderDetailPojo.getLineNo())) {
						allFeedTotal+=feedOrderDetailPojo.getFeedTotal();
					}
				}
			}
		}else {
			for(FeedOrderDetailPojo feedOrderDetailPojo:feedOrderDetailPojos) {
				//订单编号相同,并且行号不是-1
				if(orderId.equals(feedOrderDetailPojo.getOrderId())) {
					if(!"-1".equals(feedOrderDetailPojo.getLineNo()) && lineNo.equals(feedOrderDetailPojo.getLineNo())) {
						allFeedTotal+=feedOrderDetailPojo.getOrderTotal();
					}
				}
			}
		}
		return allFeedTotal;
	}
	
	/** 
	 * 获取平均投料单投料数
	 * @param feedOrderDetailPojo
	 * @return
	 */
	public double getAvgFeedCountOnStyleFive(FeedOrderDetailPojo feedOrderDetailPojo,boolean isOrderTotal) {
		BigDecimal feedCount = new BigDecimal("0.0");
		BigDecimal feedTotal = new BigDecimal("0.0");
		BigDecimal allFeedTotal = new BigDecimal("0.0");
		if(!isOrderTotal) {
			if(feedOrderDetailPojo.getAllFeedTotal()>0) {
				allFeedTotal = new BigDecimal(feedOrderDetailPojo.getAllFeedTotal()+"");
			}
			if(feedOrderDetailPojo.getFeedTotal() !=null) {
				feedTotal = new BigDecimal(feedOrderDetailPojo.getFeedTotal().toString());
			}
			if(feedOrderDetailPojo.getAllFeedTotal()==0) {
				return feedCount.doubleValue();
			}
		}else {
			if(feedOrderDetailPojo.getAllOrderTotal()>0) {
				allFeedTotal = new BigDecimal(feedOrderDetailPojo.getAllOrderTotal()+"");
			}
			if(feedOrderDetailPojo.getAllOrderTotal()==0) {
				return feedCount.doubleValue();
			}
			if(feedOrderDetailPojo.getAllOrderTotal()==0) {
				return feedCount.doubleValue();
			}
		}
		if(feedOrderDetailPojo.getFeedCount() !=null) {
			feedCount = new BigDecimal(feedOrderDetailPojo.getFeedCount().toString());
		}
		feedCount = feedTotal.divide(allFeedTotal,2,BigDecimal.ROUND_HALF_UP).multiply(feedCount);
		return feedCount.doubleValue();
	}
//	public double getAvgFeedCountOnStyleFive(FeedOrderDetailPojo feedOrderDetailPojo,boolean isOrderTotal) {
//		BigDecimal feedCount = new BigDecimal("0.0");
//		BigDecimal feedTotal = new BigDecimal("0.0");
//		BigDecimal allFeedTotal = new BigDecimal("0.0");
//		if(!isOrderTotal) {
//			if(feedOrderDetailPojo.getAllFeedTotal()>0) {
//				allFeedTotal = new BigDecimal(feedOrderDetailPojo.getAllFeedTotal()+"");
//			}
//			if(feedOrderDetailPojo.getFeedTotal() !=null) {
//				feedTotal = new BigDecimal(feedOrderDetailPojo.getFeedTotal().toString());
//			}
//			if(feedOrderDetailPojo.getAllFeedTotal()==0) {
//				return feedCount.doubleValue();
//			}
//		}else {
//			if(feedOrderDetailPojo.getAllOrderTotal()>0) {
//				allFeedTotal = new BigDecimal(feedOrderDetailPojo.getAllOrderTotal()+"");
//			}
//			if(feedOrderDetailPojo.getOrderTotal() !=null) {
//				feedTotal = new BigDecimal(feedOrderDetailPojo.getOrderTotal().toString());
//			}
//			if(feedOrderDetailPojo.getAllOrderTotal()==0) {
//				return feedCount.doubleValue();
//			}
//		}
//		if(feedOrderDetailPojo.getFeedCount() !=null) {
//			feedCount = new BigDecimal(feedOrderDetailPojo.getFeedCount().toString());
//		}
//		feedCount = feedTotal.divide(allFeedTotal,2,BigDecimal.ROUND_HALF_UP).multiply(feedCount);
//		return feedCount.doubleValue();
//	}
	
	/**
	 * 获取平均订单投料数
	 * @return
	 */
	private double getAvgFeedTotalOnStyleFive(FeedOrderDetailPojo styleFivePojo,FeedOrderDetailPojo pojo) {
		BigDecimal feedTotal = new BigDecimal("0.0");
		BigDecimal styleFiveFeedTotal = new BigDecimal("0.0");
		BigDecimal allFeedTotal = new BigDecimal("0.0");
		if(styleFivePojo.getAllFeedTotal()>0) {
			allFeedTotal = new BigDecimal(styleFivePojo.getAllFeedTotal()+"");
		}
		if(pojo.getFeedTotal() !=null) {
			feedTotal = new BigDecimal(pojo.getAllLineFeedTotal().toString());
		}
		if(styleFivePojo.getFeedTotal() !=null) {
			styleFiveFeedTotal = new BigDecimal(styleFivePojo.getFeedTotal().toString());
		}
		if(styleFivePojo.getAllFeedTotal()==0) {
			return feedTotal.doubleValue();
		}
		feedTotal = feedTotal.divide(allFeedTotal,2,BigDecimal.ROUND_HALF_UP).multiply(styleFiveFeedTotal);
		return feedTotal.doubleValue();
	}
	
	/**
	 * 获取订单眼镜成本
	* @date 2018年8月6日 下午2:11:04 
	* @author 李斌
	* @return List<OrderCostGlassesPojo> 
	* @throws
	 */ 
	public DatatablesViewPageBean<OrderCostGlassesPojo> getOrderCostGlasses(Map<String,Object> map) {
		//获取所有的投料单明细 
		List<FeedOrderDetailPojo> feedOrderDetailPojos = orderCostGlassesMapper.getAllFeedOrderDetail(map);
		List<FeedOrderDetailPojo> feedOrderDetailClone = new ArrayList<FeedOrderDetailPojo>();
		feedOrderDetailClone.addAll(feedOrderDetailPojos);
		Map<String,List<FeedOrderDetailPojo>> groupFeedMap = new HashMap<String,List<FeedOrderDetailPojo>>(); 
		//存放样式五的list
		List<FeedOrderDetailPojo> styleFive = new ArrayList<FeedOrderDetailPojo>();
		//根据订单编号分组
		Iterator<FeedOrderDetailPojo> iterator = feedOrderDetailPojos.iterator();
		//使用迭代器分组
		
		while(iterator.hasNext()) {
			FeedOrderDetailPojo feedOrderDetailPojo = iterator.next();
			int allFeedTotal = this.getAllFeedTotal(feedOrderDetailClone, feedOrderDetailPojo.getOrderId());
			Double allLineFeedTotal = this.getAllLineFeedTotal(feedOrderDetailPojos, feedOrderDetailPojo.getOrderId(), feedOrderDetailPojo.getLineNo(),false);
			feedOrderDetailPojo.setAllFeedTotal(allFeedTotal);
			feedOrderDetailPojo.setAllLineFeedTotal(allLineFeedTotal);
			if("-1".equals(feedOrderDetailPojo.getLineNo())) { 
				//将样式五的数据放入styleFive中
				styleFive.add(feedOrderDetailPojo);
				//从集合汇总剔除样式五
				iterator.remove();
			}else {
				List<FeedOrderDetailPojo> groupVal = groupFeedMap.get(feedOrderDetailPojo.getOrderId()+"lineNo"+feedOrderDetailPojo.getLineNo());
				if(groupVal==null) { 
					groupVal = new ArrayList<FeedOrderDetailPojo>();
					groupVal.add(feedOrderDetailPojo);
					groupFeedMap.put(feedOrderDetailPojo.getOrderId()+"lineNo"+feedOrderDetailPojo.getLineNo(), groupVal);
				}else { 
					groupVal.add(feedOrderDetailPojo);
				}
			}
		}
		
		List<OrderCostGlassesPojo> orderCostGlassesPojos = new ArrayList<OrderCostGlassesPojo>();
		//遍历分组后的map
		for(Entry<String, List<FeedOrderDetailPojo>> entry:groupFeedMap.entrySet()) {
			//遍历每个entryVal
			//立个标识
			int flag = 0;
			OrderCostGlassesPojo orderCostGlassesPojo = new OrderCostGlassesPojo();
			for(FeedOrderDetailPojo feedOrderDetailPojo:entry.getValue()) { 
				flag ++;
				if(flag==1) {
					BigDecimal styleFiveCostMoney = new BigDecimal("0.0");
					BigDecimal styleFiveFeedTotal = new BigDecimal("0.0");
					BigDecimal styleFiveUnitPrice = new BigDecimal("0.0");
					BigDecimal styleFiveFeedCount = new BigDecimal("0.0");
					BigDecimal styleFiveOrderCostMoney = new BigDecimal("0.0");
					for(FeedOrderDetailPojo styleFivePojo:styleFive) {
						if(feedOrderDetailPojo.getOrderId().equals(styleFivePojo.getOrderId())) {
							//还原投料单投料数和订单投料数
							styleFivePojo.setFeedCount(styleFivePojo.getOldFeedCount());
							styleFivePojo.setFeedTotal(styleFivePojo.getOldFeedTotal());
							//投料单投料数
							double feedCount = this.getAvgFeedCountOnStyleFive(styleFivePojo,false);
							double styleFiveTotal = this.getAvgFeedTotalOnStyleFive(styleFivePojo,feedOrderDetailPojo);
							styleFivePojo.setFeedCount(feedCount);
							//样式五
							styleFiveCostMoney = styleFiveCostMoney.add(calculateCost(styleFivePojo,false));
							//计算完成本后在设置订单投料数
							styleFivePojo.setFeedTotal(styleFiveTotal);
							//样式五订单投料数
							styleFiveFeedTotal =styleFiveFeedTotal.add(new BigDecimal(styleFivePojo.getFeedTotal().toString()));
							//样式五用料金额
							styleFiveUnitPrice = styleFiveUnitPrice.add(new BigDecimal(styleFivePojo.getUnitPrice().toString()));
							//样式五用料数量
							styleFiveFeedCount = styleFiveFeedCount.add(new BigDecimal(styleFivePojo.getFeedCount().toString()));
							//样式五订单成本(订单数)
							styleFiveOrderCostMoney = styleFiveOrderCostMoney.add(calculateCost(styleFivePojo,true));
						}	
					}  
					//非样式五
					BigDecimal materialCostMoney = calculateCost(feedOrderDetailPojo,false);
					//非样式五订单投料数
					BigDecimal orderFeedTotal = new BigDecimal(feedOrderDetailPojo.getFeedTotal().toString());
					//非样式五用料数量
					BigDecimal materialFeedCount = new BigDecimal(feedOrderDetailPojo.getFeedCount().toString());
					//非样式五订单成本
					BigDecimal materialOrderCostMoney = calculateCost(feedOrderDetailPojo,true);
					//成本金额+样式五成本
					orderCostGlassesPojo.setGlassesMoney(materialCostMoney.add(styleFiveCostMoney).doubleValue());
					//某行投料数+样式五投料数
					orderCostGlassesPojo.setFeedTotal(orderFeedTotal.doubleValue());
//					orderCostGlassesPojo.setFeedTotal(orderFeedTotal.add(styleFiveFeedTotal).doubleValue());
					//用量数量+样式五用量数量
					orderCostGlassesPojo.setFeedCount(materialFeedCount.add(styleFiveFeedCount).doubleValue());
					//订单订单数成本 + 样式五订单成本
					orderCostGlassesPojo.setGlassesOrderMoney(materialOrderCostMoney.add(styleFiveOrderCostMoney).doubleValue());
					//订单订单数
					orderCostGlassesPojo.setOrderTotal(feedOrderDetailPojo.getOrderTotal());
				}else {
					//非样式五物料成本 
					BigDecimal materialCostMoney = calculateCost(feedOrderDetailPojo,false);
					//非样式五订单投料数
					BigDecimal orderFeedTotal = new BigDecimal(feedOrderDetailPojo.getFeedTotal().toString());
					//非样式五物料用料数
					BigDecimal materialFeedCount = new BigDecimal(feedOrderDetailPojo.getFeedCount().toString());
					//非样式五订单成本
					BigDecimal materialOrderCostMoney = calculateCost(feedOrderDetailPojo,true);
					//非样式五订单数量
					BigDecimal orderTotal = new BigDecimal(feedOrderDetailPojo.getOrderTotal().toString());
					//老成本价
					BigDecimal oldMaterialCostMoney = new BigDecimal(orderCostGlassesPojo.getGlassesMoney()==null?"0.0":orderCostGlassesPojo.getGlassesMoney().toString());
					//老订单投料数
					BigDecimal oldOrderFeedTotal = new BigDecimal(orderCostGlassesPojo.getFeedTotal()==null?"0.0":orderCostGlassesPojo.getFeedTotal().toString());
					//老物料用料数
					BigDecimal oldMaterialFeedCount = new BigDecimal(orderCostGlassesPojo.getFeedCount()==null?"0.0":orderCostGlassesPojo.getFeedCount().toString());		
					//老物料订单成本
					BigDecimal oldMaterialOrderCostMoney = new BigDecimal(orderCostGlassesPojo.getGlassesOrderMoney()==null?"0.0":orderCostGlassesPojo.getGlassesOrderMoney().toString());
					//老物料订单数量
					BigDecimal oldOrderTotal = new BigDecimal(orderCostGlassesPojo.getOrderTotal()==null?"0.0":orderCostGlassesPojo.getOrderTotal().toString());
					//成本对象(投料)
					orderCostGlassesPojo.setGlassesMoney(oldMaterialCostMoney.add(materialCostMoney).doubleValue());
					//某行投料数
					orderCostGlassesPojo.setFeedTotal(orderFeedTotal.doubleValue());
//					orderCostGlassesPojo.setFeedTotal(orderFeedTotal.add(oldOrderFeedTotal).doubleValue());
					//物料用料数
					orderCostGlassesPojo.setFeedCount(oldMaterialFeedCount.add(materialFeedCount).doubleValue());
					//订单数量
//					orderCostGlassesPojo.setOrderTotal(oldOrderTotal.add(orderTotal).doubleValue());
					orderCostGlassesPojo.setOrderTotal(orderTotal.doubleValue());
					//成本对象(订单)
					orderCostGlassesPojo.setGlassesOrderMoney(oldMaterialOrderCostMoney.add(materialOrderCostMoney).doubleValue());
				} 
			} 
			orderCostGlassesPojo.setLineNo(entry.getValue().get(0).getLineNo());
			orderCostGlassesPojo.setOrderId(entry.getValue().get(0).getOrderId()); 
			orderCostGlassesPojo.setCompanyOrderId(entry.getValue().get(0).getCompanyOrderId()); 
			orderCostGlassesPojo.setFactoryId(entry.getValue().get(0).getFactoryId()); 
			orderCostGlassesPojo.setCustomerId(entry.getValue().get(0).getCustomerId()); 
			orderCostGlassesPojo.setCustomerOrderId(entry.getValue().get(0).getCustomerOrderId()); 
			orderCostGlassesPojos.add(orderCostGlassesPojo);
		}
		
		//分页
		int start = 0;
		int length = 0;
		int end = 0;
		if(map.get("start")!=null) {
			start = Integer.parseInt(map.get("start").toString());
		}
		if(map.get("length")!=null) {
			length = Integer.parseInt(map.get("length").toString());
		}
		int count = orderCostGlassesPojos.size();
		end = start+length;
		if(end>count) {
			end = count; 
		}
		
		List<OrderCostGlassesPojo> returnList=orderCostGlassesPojos.subList(start, end);
		returnList=this.getPeopleAndManagerGlasses(returnList, map.get("loginCompany").toString(), feedOrderDetailPojos);
		DatatablesViewPageBean<OrderCostGlassesPojo> datatablesViewPageBean = new DatatablesViewPageBean<OrderCostGlassesPojo>();
		datatablesViewPageBean.setiTotalDisplayRecords(count);
		datatablesViewPageBean.setiTotalRecords(count);
		datatablesViewPageBean.setReturnData(returnList);
		return datatablesViewPageBean;
	}
	
	
	/**
	 * 计算眼镜成本
	* @date 2018年8月7日 上午8:41:24 
	* @author 李斌
	* @return BigDecimal 
	* @throws
	 */
	private BigDecimal calculateCost(FeedOrderDetailPojo feedOrderDetailPojo,boolean isOrderTotal) {
		//物料单价
		BigDecimal materialUnitPrice = new BigDecimal(feedOrderDetailPojo.getUnitPrice().toString());
		//物料单位投料数
		BigDecimal materialFeedCount = new BigDecimal(feedOrderDetailPojo.getFeedCount().toString());
		//订单投料数
		BigDecimal orderFeedTotal = null;
		if(!isOrderTotal) {
			orderFeedTotal = new BigDecimal(feedOrderDetailPojo.getFeedTotal().toString());
		}else {
			orderFeedTotal = new BigDecimal(feedOrderDetailPojo.getOrderTotal().toString());
		}
		//成本==单价*投料单投料数/订单投料数
		if(orderFeedTotal.doubleValue()<=0) {
			return new BigDecimal("0.0");
		}
		BigDecimal calculateCostMoney = materialFeedCount.multiply(materialUnitPrice).divide(orderFeedTotal,2);
		return calculateCostMoney;
	}
	
	public List<OrderCostGlassesPojo> getOrderLineDetailList(Map<String, Object> map) {
		//获取所有的投料单明细分行号
		List<FeedOrderDetailPojo> feedOrderDetailPojos = orderCostGlassesMapper.getAllFeedOrderDetail(map);
		//获取某订单所有的投料信息
		map.remove("lineNo");
		List<FeedOrderDetailPojo> allFeedOrderDetailPojosNotLine = orderCostGlassesMapper.getAllFeedOrderDetail(map);
		//用于返回的订单成本list
		List<OrderCostGlassesPojo> orderCostGlassesPojos = new ArrayList<OrderCostGlassesPojo>();
		for(FeedOrderDetailPojo feedOrderDetailPojo:feedOrderDetailPojos) {
			//非样式五订单总投料数
			int allFeedTotal = this.getAllFeedTotal(allFeedOrderDetailPojosNotLine, feedOrderDetailPojo.getOrderId());
			feedOrderDetailPojo.setAllFeedTotal(allFeedTotal);
			double avgFeedTotal = feedOrderDetailPojo.getFeedTotal();
			double avgStyleFiveFeedCount = feedOrderDetailPojo.getFeedCount();
			double allOrderTotal = allFeedOrderDetailPojosNotLine.stream().filter(feed->feedOrderDetailPojo.getOrderId().equals(feed.getOrderId()) && !"-1".equals(feed.getLineNo())).mapToDouble(FeedOrderDetailPojo::getOrderTotal).sum();
			feedOrderDetailPojo.setAllOrderTotal(allOrderTotal);
			//平均订单数
			double avgOrderTotal = feedOrderDetailPojo.getOrderTotal();
			for(FeedOrderDetailPojo pojo:feedOrderDetailPojos) {
				//如果是样式五的
				if("-1".equals(feedOrderDetailPojo.getLineNo()) && !"-1".equals(pojo.getLineNo())) {
					//非样式五订单行投料数
					Double allLineFeedTotal = this.getAllLineFeedTotal(feedOrderDetailPojos, feedOrderDetailPojo.getOrderId(), pojo.getLineNo(),false);
					pojo.setAllLineFeedTotal(allLineFeedTotal);
					avgFeedTotal = this.getAvgFeedTotalOnStyleFive(feedOrderDetailPojo, pojo);
					break;
				} 
			}
			if("-1".equals(feedOrderDetailPojo.getLineNo())) {
				//平均样式五投料单投料数
				avgStyleFiveFeedCount = this.getAvgFeedCountOnStyleFive(feedOrderDetailPojo,false);
				//平均样式五订单订单数
				avgOrderTotal = this.getAvgFeedCountOnStyleFive(feedOrderDetailPojo,true);
				feedOrderDetailPojo.setFeedCount(avgStyleFiveFeedCount);
				feedOrderDetailPojo.setOrderTotal(avgOrderTotal);
			}
			OrderCostGlassesPojo orderCostGlassesPojo = new OrderCostGlassesPojo(feedOrderDetailPojo);
			orderCostGlassesPojo.setGlassesMoney(calculateCost(feedOrderDetailPojo,false).doubleValue());
			orderCostGlassesPojo.setGlassesOrderMoney(calculateCost(feedOrderDetailPojo,true).doubleValue());
			orderCostGlassesPojo.setFeedTotalDetail(avgFeedTotal+"");
			orderCostGlassesPojo.setOrderTotalDetail(avgOrderTotal+"");
			orderCostGlassesPojos.add(orderCostGlassesPojo);
		}
		return orderCostGlassesPojos;
	}

	/**
	 * 获取订单编号list
	* @date 2018年8月8日 下午1:18:28 
	* @author 李斌 
	* @return List<String> 
	* @throws
	 */
	public List<MaterialSelectFilterPojo> getOrderIdList(Map<String, Object> map) {
		return orderCostGlassesMapper.getOrderIdList(map);
	}
	
	
	
	
	/**
	 * 获取人工成本和管理成本
	 * @param paramList
	 * @return
	 */
	public List<OrderCostGlassesPojo> getPeopleAndManagerGlasses(List<OrderCostGlassesPojo> paramList,String loginCompany,List<FeedOrderDetailPojo> feedOrderDetailPojos){
		if(null==paramList || paramList.size()<=0) {
			return paramList;
		}
		//单个订单总投料数map
		Map<String,Double> orderSumFeedMap=new HashMap<String,Double>();
		//获取公司月管理成本
		FeedingAndReportBean managerMap=orderCostGlassesMapper.getCompanyManagerData(loginCompany);
		double manager=managerMap.getMonthlySalary().divide(managerMap.getDailyCapacity(), 2).doubleValue();
		Set<String> orderIdSet=paramList.stream().map(OrderCostGlassesPojo::getOrderId).collect(Collectors.toSet());
		//获取计算人工成本所需数据
		List<ProcessBean> orderProcessList=orderCostGlassesMapper.getPeopleGlassesData(orderIdSet);
		
		//获取公司预设成本所需数据
		List<ProcessBean> treeProcessList=orderCostGlassesMapper.getOrderTreeProcessByOrderList(orderIdSet);
		List<ProcessBean> setProcessList=orderCostGlassesMapper.getOrderSetProcessByOrderList(orderIdSet);
		
		
		Map<String, Double> yuMap=new HashMap<String,Double>();
		for(int i=0;i<paramList.size();i++) {
			OrderCostGlassesPojo oneParam=paramList.get(i);
			//设置预设成本
			if(null==yuMap.get(oneParam.getOrderId())) {
				List<ProcessBean> yuProcedure=treeProcessList.stream().filter(pp->pp.getOrderId().equals(oneParam.getOrderId())).collect(Collectors.toList());
			    if(yuProcedure.size()<=0) {
			    	yuProcedure=setProcessList.stream().filter(pp->pp.getOrderId().equals(oneParam.getOrderId())).collect(Collectors.toList());
			    }
			    if(yuProcedure.size()<=0) {
			    	yuMap.put(oneParam.getOrderId(), 0.0);
			    }else {
			    	Double notKuab=yuProcedure.stream().filter(pp->!"款".equals(pp.getChargeUnit())).mapToDouble(ProcessBean::getUnitPrice).sum();
			    	List<ProcessBean> list=yuProcedure.stream().filter(pp->"款".equals(pp.getChargeUnit())).collect(Collectors.toList());
			    	yuMap.put(oneParam.getOrderId(), this.getOrderProcedureCost(list,orderSumFeedMap,oneParam,notKuab,feedOrderDetailPojos));
			    }
			}
			
			//不是款的总价
			Double notKuanPrice=orderProcessList.stream().filter(pp->pp.getOrderId().equals(oneParam.getOrderId()) && (pp.getRowIndex().equals(oneParam.getLineNo()) || "-1".equals(pp.getRowIndex())) && !"款".equals(pp.getChargeUnit())).mapToDouble(ProcessBean::getUnitPrice).sum();
			List<ProcessBean> oneProcessList =orderProcessList.stream().filter(pp->pp.getOrderId().equals(oneParam.getOrderId()) && (pp.getRowIndex().equals(oneParam.getLineNo()) || "-1".equals(pp.getRowIndex())) && "款".equals(pp.getChargeUnit())).collect(Collectors.toList());
		    Double xx=this.getOrderProcedureCost(oneProcessList,orderSumFeedMap,oneParam,notKuanPrice,feedOrderDetailPojos);
		    oneParam.setPeopleCost(xx);
		    oneParam.setManagerCost(manager);
		    oneParam.setYuCost(yuMap.get(oneParam.getOrderId()));
		}
		return paramList;
	}

	/**
	 * 获取订单不是款工序的价格
	 * @param oneProcessList(订单款工序)
	 * @param orderSumFeedMap (订单总投料数map)
	 * @param oneParam (当前订单信息)
	 * @param notKuanPrice (不是款价格)
	 * @param feedOrderDetailPojos (投料数信息)
	 * 价格为   款的价格/订单那总投料数
	 * @return
	 */
	private Double getOrderProcedureCost(List<ProcessBean> oneProcessList, Map<String, Double> orderSumFeedMap, OrderCostGlassesPojo oneParam, Double notKuanPrice, List<FeedOrderDetailPojo> feedOrderDetailPojos) {
		Double kuanPrice=0.00;
		if(oneProcessList.size()>0) {
	    	//如果订单没有计算过总数
	    	if(null==orderSumFeedMap.get(oneParam.getOrderId())) {
	    		Double ordrSumFeedCount=this.getOrderSumFeedCount(oneParam.getOrderId(),feedOrderDetailPojos);
	    		orderSumFeedMap.put(oneParam.getOrderId(), ordrSumFeedCount);
	    	}
	    	kuanPrice=oneProcessList.stream().mapToDouble(ProcessBean::getUnitPrice).sum();
	    	BigDecimal orderFeddCount=new BigDecimal(orderSumFeedMap.get(oneParam.getOrderId()).toString());
	    	BigDecimal kuan=new BigDecimal(kuanPrice.toString());
	    	kuanPrice=kuan.divide(orderFeddCount, 2).doubleValue();
	    }
	    BigDecimal no=new BigDecimal(notKuanPrice.toString());
	    BigDecimal kuan=new BigDecimal(kuanPrice.toString());
	    no=no.add(kuan);
	    notKuanPrice=no.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
	    return notKuanPrice;
	}

	/**
	 * 获取每个订单总投料数
	 * @param orderId
	 * @param feedOrderDetailPojos
	 * @return
	 */
	private Double getOrderSumFeedCount(String orderId, List<FeedOrderDetailPojo> feedOrderDetailPojos) {
		double sumCount=0.0;
		//单个订单数据
		List<FeedOrderDetailPojo> orderList=feedOrderDetailPojos.stream().filter(pp->pp.getOrderId().equals(orderId) && !"-1".equals(pp.getLineNo())).collect(Collectors.toList());
		Map<String, List<FeedOrderDetailPojo>> lineNoGroup=orderList.stream().collect(Collectors.groupingBy(FeedOrderDetailPojo::getLineNo));
		for(String lineNo:lineNoGroup.keySet()) {
			double count=lineNoGroup.get(lineNo).stream().mapToDouble(FeedOrderDetailPojo::getFeedTotal).min().getAsDouble();
			sumCount=sumCount+count;
		}
		//如果整个订单只有-1行，投料数按1处理
		if(sumCount == 0) {
			sumCount = 1;
		}
		return sumCount;
	}
	
	/**
	 * desc 获取个人申补金额
	 * param data,userId,company
	 * @return
	 */
	public List<ApplyRepairMoneyPojo> getApplyRepairOrderMoney(String startDate,String endDate,Integer userId,String companyName) {
		Assert.isTrue(companyName !=null && !companyName.trim().isEmpty(), "公司名不能为空");
		//根据用户获取所有申补单信息(审核/未审核)
		List<ApplyRepairMoneyPojo> applyRepairMoneyPojo = orderCostGlassesMapper.getApplyRepairOrderMoney(startDate,endDate,userId,companyName);
		Map<Integer,List<ApplyRepairMoneyPojo>> groupMap = groupList(applyRepairMoneyPojo);
		List<ApplyRepairMoneyPojo> resultList = new ArrayList<ApplyRepairMoneyPojo>();
		for(Entry<Integer, List<ApplyRepairMoneyPojo>> entry:groupMap.entrySet()) {
			BigDecimal allMoney = new BigDecimal("0.0");
			List<ApplyRepairMoneyPojo> list = entry.getValue();
			ApplyRepairMoneyPojo userRepairMoneyPojo = new ApplyRepairMoneyPojo();
			for(ApplyRepairMoneyPojo applyRepairMoney:entry.getValue()) {
				allMoney = allMoney.add(getOneApplyRepairMoney(applyRepairMoney));
			}
			userRepairMoneyPojo.setAllMoney(allMoney.doubleValue());
			userRepairMoneyPojo.setUserId(list.get(0).getUserId());
			resultList.add(userRepairMoneyPojo);
		}
		return resultList;
	}
	
	private BigDecimal getOneApplyRepairMoney(ApplyRepairMoneyPojo applyRepairMoneyPojo) {
		//总承担比例
		BigDecimal allShaseTax = new BigDecimal("100");
		//申补物料总金额
		BigDecimal allMoney = new BigDecimal(applyRepairMoneyPojo.getAllMoney().toString());
		BigDecimal companyShareTax = new BigDecimal(applyRepairMoneyPojo.getCompanyShare().toString());
		BigDecimal peopleShareTax = new BigDecimal(applyRepairMoneyPojo.getPeopleShare().toString());
		//人员承担总金额 = allMoney * (100-companyShareTax)/100
		BigDecimal peopleShareAllMoney = allMoney.multiply(allShaseTax.subtract(companyShareTax)).divide(allShaseTax,2,BigDecimal.ROUND_HALF_DOWN);
		//个人承担金额 = peopleShareAllMoney*peopleShareTax/100
		BigDecimal peopleShareMoney = peopleShareAllMoney.multiply(peopleShareTax).divide(allShaseTax);
		return peopleShareMoney;
	}
	
	private Map<Integer,List<ApplyRepairMoneyPojo>> groupList(List<ApplyRepairMoneyPojo> list){
		Map<Integer,List<ApplyRepairMoneyPojo>> groupMap = new HashMap<Integer,List<ApplyRepairMoneyPojo>>();
		Iterator<ApplyRepairMoneyPojo> iterable = list.iterator();
		while(iterable.hasNext()) {
			ApplyRepairMoneyPojo next = iterable.next();
			List<ApplyRepairMoneyPojo> groupVal = groupMap.get(next.getUserId());
			if(groupVal==null) { 
				groupVal = new ArrayList<ApplyRepairMoneyPojo>();
				groupVal.add(next);
				groupMap.put(next.getUserId(), groupVal);
			}else { 
				groupVal.add(next);
			}
		}
		return groupMap;
	}

	/**
	 * 获取设备订单的成本
	 * @param map
	 * @return
	 */
	public DatatablesViewPageBean<OrderCostGlassesPojo> getMachineCostGlasses(Map<String, Object> map) {
		//订单投料信息
		List<FeedOrderDetailPojo> feedOrderDetailPojos = orderCostGlassesMapper.getAllFeedOrderDetail(map);
	    //设备订单完成情况
		List<OrderCostGlassesPojo> list=orderCostGlassesMapper.getMachineCostGlasses(map);
	    //完成数量
		int count=orderCostGlassesMapper.getMachineCostGlassesCount(map);
	    if(count>0) {
	    	List<CompanyMaterialTableBean>  detailList=orderCostGlassesMapper.getMachingOrderDetail(list);
	    	Map<String, List<CompanyMaterialTableBean>> ordersMap=detailList.stream().collect(Collectors.groupingBy(CompanyMaterialTableBean::getOrderId));
	        for(OrderCostGlassesPojo orderCostGlassesPojo:list) {
	        	List<CompanyMaterialTableBean> orderDetail=ordersMap.get(orderCostGlassesPojo.getOrderId());
	        	if(null!=orderDetail) {
	        		double price=orderDetail.stream().mapToDouble(CompanyMaterialTableBean::getUnitPrice).sum();
	        		orderCostGlassesPojo.setGlassesMoney(price);
	        		orderCostGlassesPojo.setGlassesOrderMoney(price);
	        	}
	        }
//	        list=this.setMachinePeopleCost(list,map);
	        list=this.getPeopleAndManagerGlasses(list, map.get("loginCompany").toString(), feedOrderDetailPojos);
	    }
	    //设置设备人工成本
	    DatatablesViewPageBean<OrderCostGlassesPojo> datatablesViewPageBean=new DatatablesViewPageBean<OrderCostGlassesPojo>();
	    datatablesViewPageBean.setReturnData(list);
	    datatablesViewPageBean.setiTotalDisplayRecords(count);
	    datatablesViewPageBean.setiTotalRecords(count);
	    return datatablesViewPageBean; 
	}

	
   /**
    * 设置设备人工成本
    * @param list
    * @param map
    * @return
    */
	private List<OrderCostGlassesPojo> setMachinePeopleCost(List<OrderCostGlassesPojo> list, Map<String, Object> map) {
		 Set<String> monthSet=list.stream().map(OrderCostGlassesPojo::getMonth).collect(Collectors.toSet());
		 Map<String, Double> monthGost=new HashMap<String, Double>();
		 Map paramMap=new HashMap();
		 paramMap.put("loginCompany", map.get("loginCompany"));
		 for(String month:monthSet) {
			 if(!"".equals(month)) {
				Double returnValue=0.0;
				String startDate=month+"-01";
				String endDate=this.getThisMonthLastDay(month);
			    paramMap.put("startDate", startDate);
				paramMap.put("endDate", endDate);
				try {
					DatatablesViewPageBean<AttendanceMonthSummaryBean> datatablesViewPageBean=attendanceService.getMonthSummaryByDeptAndWorkshop(paramMap);
				    List<AttendanceMonthSummaryBean> detailList=datatablesViewPageBean.getReturnData();
				    returnValue=detailList.stream().mapToDouble(AttendanceMonthSummaryBean::getRealSalary).sum();
				} catch (Exception e) {
					returnValue=0.0;
				}
				paramMap.put("month", month);
				Integer count=orderCostGlassesMapper.getMonthFinishMachingCount(paramMap);
				count=count==0?1:count;
				monthGost.put(month, returnValue/count);
			 }
		 }
		 //设置人工成本
		 list.forEach(o->{
			 if("".equals(o.getMonth())) {
				 o.setPeopleCost(0.0);
			 }else {
				 o.setPeopleCost(monthGost.get(o.getMonth())==null?0:monthGost.get(o.getMonth()));
			 }
		 });
		 return list;
	}

	/**
	 * 获取当月最后一填
	 * @param month
	 * @return
	 */
	private String getThisMonthLastDay(String month) {
		String  day=month+"-28";
		String[] xx=month.split("-");
		int monthInt=Integer.parseInt(xx[1]);
		switch (monthInt) {
		  case 1:day=month+"-31";break;
		  case 3:day=month+"-31";break;
		  case 5:day=month+"-31";break;
		  case 7:day=month+"-31";break;
		  case 8:day=month+"-31";break;
		  case 10:day=month+"-31";break;
		  case 12:day=month+"-31";break;
		  case 2:day=month+"-28";break;
		  case 4:day=month+"-30";break;
		  case 6:day=month+"-30";break;
		  case 9:day=month+"-30";break;
		  case 11:day=month+"-30";break;
		}
		return day;
	}
	
}
